﻿using System;
namespace StableDiffusionTools.Progress
{
    public class UpdateThrottler
    {
        public event UpdateEvent Update;
        protected virtual void OnUpdate(UpdateEventArgs e) => Update?.Invoke(this, e);

        public int UpdateTime { get; set; }
        public bool ReadyForUpdate { get => IsReadyForUpdate(); }

        DateTime LastUpdate = DateTime.Now;
        TimeSpan TotalElapsed = TimeSpan.Zero;

        public UpdateThrottler(int updateTimeMS = 25) => UpdateTime = updateTimeMS;

        private bool IsReadyForUpdate()
        {
            bool bReturn = false;

            DateTime now = DateTime.Now;
            TimeSpan delta = now - LastUpdate;

            if (delta.TotalMilliseconds >= UpdateTime)
            {
                LastUpdate = now;
                TotalElapsed += delta;
                OnUpdate(new UpdateEventArgs(delta, TotalElapsed));
                bReturn = true;
            }

            return bReturn;
        }
    }
}
